package com.github.tvbox.osc.ui.activity.Media

import android.content.Context
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.IdRes
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.github.tvbox.osc.R
import com.github.tvbox.osc.event.PlayEvent
import com.github.tvbox.osc.ui.adapter.SeriesAdapter
import com.github.tvbox.osc.ui.adapter.SeriesFlagAdapter
import com.github.tvbox.osc.util.FastClickCheckUtil
import com.owen.tvrecyclerview.widget.SimpleOnItemListener
import com.owen.tvrecyclerview.widget.TvRecyclerView
import com.owen.tvrecyclerview.widget.V7GridLayoutManager
import com.owen.tvrecyclerview.widget.V7LinearLayoutManager
import io.github.source.bean.Episode
import io.github.source.bean.Flag
import io.github.source.media.bean.MediaBean

/**
 * @ClassName: MediaVodPanelView
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author: huangrongcai
 * @date: 2024/8/22
 *
 * @Copyright: 黄嵘才（HuangRc)
 */
class MediaVodPanelView {
    private val TAG = "APP.Media.vodPanelView"

    private var mView: View? = null
    private var mEmptyPlayList: View? = null

    /**
     * 专辑标签
     */
    private var mGridViewFlag: TvRecyclerView? = null
    private var mGridViewEpisode: TvRecyclerView? = null

    private val mFlagAdapter by lazy { SeriesFlagAdapter() }
    private val mEpisodeAdapter by lazy { SeriesAdapter() }
    private var curSeriesIndex = 0

    private var mediaBean: MediaBean? = null

    companion object {
        @JvmStatic
        public fun create(view: View?): MediaVodPanelView {
            return MediaVodPanelView(view)
        }

    }

    constructor(view: View?) {
        mView = view
        mEmptyPlayList = findViewById<View>(R.id.mEmptyPlaylist)
        mGridViewFlag = findViewById<TvRecyclerView>(R.id.mGridViewFlag)
        mGridViewEpisode = findViewById<TvRecyclerView>(R.id.mGridView)
        setGridView()
    }


    private fun <T : View?> findViewById(@IdRes id: Int): T {
        return getView()!!.findViewById(id)
    }

    fun getView(): View? {
        return mView
    }

    fun setMediaVodPanel(mediaBean: MediaBean) {
        this.mediaBean = mediaBean
        setMediaFlag(mediaBean.vodFlags, mediaBean.playFlag)
    }


    private fun setGridView() {
        mGridViewFlag!!.setHasFixedSize(true)
        mGridViewFlag!!.layoutManager = V7LinearLayoutManager(context(), 0, false)
        mGridViewFlag!!.adapter = getFlagAdapter()
        mGridViewEpisode!!.setHasFixedSize(true)
        mGridViewEpisode!!.layoutManager = V7GridLayoutManager(context(), if (true) 6 else 7)
        mGridViewEpisode!!.adapter = getEpisodeAdapter()
    }

    private fun getEpisodeAdapter(): SeriesAdapter {
        return mEpisodeAdapter
    }

    private fun getFlagAdapter(): SeriesFlagAdapter {
        return mFlagAdapter
    }

    /**
     * 设置专辑标签
     *
     * @param flags    标签s
     * @param position 默认选中的标签
     */
    private fun setMediaFlag(flags: List<Flag>?, position: Int) {
        Log.d(TAG, "position: $position, flags: $flags")
        if (flags != null && !flags.isEmpty()) {
            mFlagAdapter!!.setNewData(flags)
            val selectedFlag = flags[position]
            //选中标签
            if (position >= 0) {
                mGridViewFlag!!.selectedPosition = position
                selectedFlag.setActivated(selectedFlag)
                performVodFlagClick(position)
            }
            setFlagViewVisibility(View.VISIBLE)
            // 更新选集和滑动到选中项目
            if (selectedFlag != null) {
                setSeriesData(selectedFlag.episodes, selectedFlag.position)
            }
        }
    }

    /**
     * 设置专辑集数
     *
     * @param episodes 专辑
     * @param position 集数
     */
    fun setSeriesData(episodes: List<Episode>?, position: Int) {
        Log.d(TAG, "episodes: $episodes")
        if (episodes != null) {
            mEpisodeAdapter!!.setNewData(episodes)
            if (position >= 0) {
                val selectedEpisode = episodes[position]
                selectedEpisode.isActivated = true
                mGridViewEpisode!!.selectedPosition = position
                onSeriesItemClick(position)
            }
        }
    }

    fun setSeriesData(episodes: List<Episode>?) {
        setSeriesData(episodes, -1)
    }

    fun getFlag(position: Int): Flag {
        return mFlagAdapter!!.data[position]
    }

    fun getFlag(): Flag {
        return getFlag(getFlagPosition())
    }

    fun getFlagSize(): Int {
        return mFlagAdapter!!.data.size
    }

    fun getData(): List<Flag> {
        return mFlagAdapter!!.data
    }


    fun setFlagViewVisibility(visibility: Int) {
        mGridViewFlag!!.visibility = visibility
        if (View.VISIBLE == visibility) {
            mEmptyPlayList!!.visibility = View.GONE
        }
    }

    fun notifyFlagItemChanged(position: Int) {
        mFlagAdapter!!.notifyItemChanged(position)
    }

    private fun context(): Context? {
        return mView!!.context
    }

    fun setOnFlagItemClickListener(listener: ItemClickListener?) {
        mFlagItemClickListener = listener
        mGridViewFlag!!.setOnItemListener(object : SimpleOnItemListener() {
            override fun onItemSelected(parent: TvRecyclerView, itemView: View, position: Int) {
                Toast.makeText(
                    context(),
                    "标签 选中了第" + (position + 1) + "个item",
                    Toast.LENGTH_SHORT
                ).show()
                onVodFlagClick(itemView, position)
            }

            override fun onItemClick(parent: TvRecyclerView, itemView: View, position: Int) {
                onVodFlagClick(itemView, position)
            }
        })
    }

    fun setOnSeriesItemClickListener(listener: IMediaAction?) {
        mIMediaAction = listener
        mEpisodeAdapter!!.setOnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View, position: Int ->
            onSeriesItemSelected(
                view,
                position
            )
        }
    }

    private fun onSeriesItemClick(position: Int) {
        val holder = mGridViewEpisode!!.findViewHolderForAdapterPosition(position)
        if (holder != null) {
            val view = holder.itemView
            mEpisodeAdapter!!.setOnItemClick(view, position)
        }
    }

    private fun refreshSeries(itemView: View, position: Int) {
        if (mediaBean == null) {
            return
        }
        //切换标签
        if (mediaBean!!.playFlag != position) {
            //刷新不选中的
            val size = getFlagSize()
            var i = 0
            while (i < size) {
                val flag = getData()[i]
                if (i == mediaBean!!.playFlag) {
                    flag.isActivated = false
                    notifyFlagItemChanged(i)
                    break
                }
                i++
            }
            //刷新选中的
            val flag = getData()[position]
            Log.d(TAG, "flag: $flag")
            flag.setActivated(flag)
            setPlayFlagPosition(position)
            notifyFlagItemChanged(position)
            //设置集数
            setSeriesData(flag.episodes)
        }
    }

    private fun onVodFlagClick(itemView: View, position: Int) {
        Toast.makeText(context(), "标签 点中了第" + (position + 1) + "个item", Toast.LENGTH_SHORT)
            .show()
        refreshSeries(itemView, position)
        mFlagItemClickListener!!.onItemClick(this@MediaVodPanelView, itemView, position)
    }

    private fun performVodFlagClick(position: Int) {
        val holder = mGridViewFlag!!.findViewHolderForAdapterPosition(position)
        if (holder != null) {
            val view = holder.itemView
            mFlagAdapter!!.setOnItemClick(view, position)
        }
    }


    private fun onSeriesItemSelected(view: View, position: Int) {
        Toast.makeText(context(), "选中了第" + (position + 1) + "个item", Toast.LENGTH_SHORT).show()
        FastClickCheckUtil.check(view)
        val episode = getEpisode()
        Log.d(TAG, "episode: $episode")
        if (episode != null) {
            /*处理选中*/
            val oldIndex = curSeriesIndex
            curSeriesIndex = position
            val newIndex = curSeriesIndex
            if (oldIndex != newIndex) {
                //处理旧的选中（从选中到未选中）
                mEpisodeAdapter!!.data[oldIndex].isActivated = false
                mEpisodeAdapter!!.notifyItemChanged(oldIndex)
            }
            mEpisodeAdapter!!.data[newIndex].isActivated = true
            mEpisodeAdapter!!.notifyItemChanged(newIndex)
            toggleSeries(newIndex)
            if (mIMediaAction != null) {
                mIMediaAction!!.onItemClick(this@MediaVodPanelView, view, position)
            }
        }
    }

    private fun toggleSeries(position: Int) {
        val oldIndex = curSeriesIndex
        curSeriesIndex = position
        val newIndex = curSeriesIndex
        getFlag().position = position
    }

    private fun setPlayFlagPosition(position: Int) {
        mediaBean!!.playFlag = position
    }

    fun getPlayFlagPosition(): Int {
        return mediaBean!!.playFlag
    }


    /**
     * 是不是准备就绪
     *
     * @return true 是的
     */
    fun isPlayListReady(): Boolean {
        if (mediaBean == null) {
            return false
        }
        val flagList = getFlags() ?: return false
        return true
    }

    fun getFlags(): List<Flag>? {
        return mediaBean?.vodFlags
    }

    fun getEpisodeUrl(): String? {
        try {
            val episode = getEpisode()
            return episode.url
        } catch (e: Exception) {
            Log.e("getEpisodeUrl", e.message!!)
        }
        return ""
    }

    fun getVodId(): String? {
        return mediaBean?.vodId
    }

    /**
     * 获取选中的点播
     */
    fun getEpisode(): Episode {
        return getEpisode(getEpisodePosition())
    }

    fun getEpisode(position: Int): Episode {
        return getEpisodeAdapter().data[position]
    }

    private fun setEpisodeSelected(position: Int) {}

    /**
     * 获取选中的点播位置
     */
    fun getEpisodePosition(): Int {
        val size = getEpisodeAdapter().data.size
        var i = 0
        while (i < size) {
            if (getEpisodeAdapter().data[i].isActivated) return i
            i++
        }
        return 0
    }

    fun getFlagPosition(): Int {
        val size = getFlagAdapter().data.size
        var i = 0
        while (i < size) {
            if (getFlagAdapter().data[i].isActivated) return i
            i++
        }
        return 0
    }

    interface IMediaAction {
        fun onItemClick(adapter: MediaVodPanelView?, view: View?, position: Int)
    }

    var mFlagItemClickListener: ItemClickListener? = null
    var mIMediaAction: IMediaAction? = null

    interface ItemClickListener {
        fun onItemClick(adapter: MediaVodPanelView?, view: View?, position: Int)
    }


    /**
     * 播放
     *
     * @param flagPosition    位置
     * @param episodePosition 位置
     */
    fun setMediaVodPanel(flagPosition: Int, episodePosition: Int) {}

    /**
     * 播放下一个
     */
    fun setNext() {
        var current = getEpisodePosition()
        val max = mEpisodeAdapter!!.data.size - 1
        current = if (++current > max) max else current
        val item = mEpisodeAdapter!!.data[current]
        if (item.isActivated) {
            //已选中
        } else setEpisodeActivated(item)
    }

    /**
     * 播放上一个
     */
    fun setPrev() {
        var current = getEpisodePosition()
        current = if (--current < 0) 0 else current
        val item = mEpisodeAdapter!!.data[current]
        if (item.isActivated) {
        } else setEpisodeActivated(item)
    }

    fun setEpisodeActivated(item: Episode?) {
        val flagPosition = getFlagPosition()
        val size = getFlagAdapter().data.size
        var i = 0
        while (i < size) {
            getFlagAdapter().data[i].toggle(flagPosition == i, item)
            i++
        }
        /*模拟点击*/onSeriesItemClick(getEpisodePosition())
    }

    private fun getEpisodeView(): RecyclerView? {
        return mGridViewEpisode
    }

    private fun getFlagView(): RecyclerView? {
        return mGridViewFlag
    }

    /*@Subscribe(threadMode = ThreadMode.MAIN)*/
    fun onPlayEvent(event: PlayEvent) {
        if (event.type == PlayEvent.PLAY_NEXT) {
            setNext()
            Toast.makeText(context(), "播放下一个", Toast.LENGTH_SHORT).show()
        }
        if (event.type == PlayEvent.PLAY_PREV) {
            setPrev()
            Toast.makeText(context(), "播放上一个", Toast.LENGTH_SHORT).show()
        }
    }
}